package First;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.IntToDoubleFunction;

public class CardUtil {
    public Map<String, MobileCard> cards = new HashMap<>();//卡信息
    public Map<String, List<ConsumInfo>> consumInfos = new HashMap<>();//用户链表信息
    public Scanner sc = new Scanner(System.in);
    public Random random = new Random();
    // 初始化测试数据
    public void initScene() {
        ServicePackage talkPack = new TalkPackage(58);
        ServicePackage superPack = new SuperPackage(78);
        ServicePackage netPack = new NetPackage(68);
        // 测试卡 可以拿来测试
        MobileCard card1 = new MobileCard("13900000000", "张三", "123456", talkPack, 100);
        MobileCard card2 = new MobileCard("13900000001", "李四", "654321", superPack, 200);
        MobileCard card3 = new MobileCard("13900137002", "王五", "111111", netPack, 150);
        // 添加到集合
        cards.put(card1.getCardNumber(), card1);
        cards.put(card2.getCardNumber(), card2);
        cards.put(card3.getCardNumber(), card3);
        // 初始化消费记录
        consumInfos.put(card1.getCardNumber(), new ArrayList<>());
        consumInfos.put(card2.getCardNumber(), new ArrayList<>());
        consumInfos.put(card3.getCardNumber(), new ArrayList<>());
        // 添加一些消费记录 方便测试！
        addConsumInfo(card1.getCardNumber(), new ConsumInfo(card1.getCardNumber(), "通话", 30, 0));
        addConsumInfo(card2.getCardNumber(), new ConsumInfo(card2.getCardNumber(), "流量", 500, 0));
        addConsumInfo(card3.getCardNumber(), new ConsumInfo(card3.getCardNumber(), "短信", 20, 0));
    }
    //卡号密码
    public boolean isExistCard(String number, String passWord) {
        MobileCard card = cards.get(number);
        return card != null && card.getPassWord().equals(passWord);
    }
    //卡号
    public boolean isExistCard(String number) {
        return cards.containsKey(number);
    }
    //随机号
    public String createNumber() {
        String number;
        do {
            StringBuilder sb = new StringBuilder("139");
            for (int i=0;i<8;i++) {//生成八位数 3+8=11
                sb.append(random.nextInt(10));//0-9随机数
            }
            number = sb.toString();
        } while (isExistCard(number));//存在就继续生成 防止有一样的号码 但是应该几率小(我猜的)
        return number;
    }
    // 获取多个新卡号
    public String[] getNewNumbers(int count) {
        String[] numbers=new String[count];
        for (int i=0;i<count;i++) {
            numbers[i] = createNumber();
        }
        return numbers;
    }
    // 添加手机卡
    public void addCard(MobileCard card) {
        cards.put(card.getCardNumber(), card);//put和get总是忘记
        consumInfos.put(card.getCardNumber(), new ArrayList<>());//加入用户链表中进行存储
    }
    // 删除手机卡
    public void delCard(String number) {
        cards.remove(number);//直接使用remove
        consumInfos.remove(number);
    }
    //余量
    public void showRemainDetail(String number) {
        MobileCard card = cards.get(number);//第一步先获取号码
        if (card != null) {
            System.out.println("卡号:" + number);
            System.out.println("用户名:" + card.getUserName());
            ServicePackage pack = card.getSerPackage();//获取套餐类型包
            if (pack instanceof TalkPackage) {//instanceof 是否包含
                TalkPackage tp = (TalkPackage) pack;//父转子
                System.out.println("剩余通话时长:" +tp.getTalkTime()+"分钟");
                System.out.println("剩余短信条数:" +tp.getSmsCount()+"条");
            } else if (pack instanceof NetPackage) {
                NetPackage np = (NetPackage) pack;
                System.out.println("剩余上网流量:" +np.getFlow()+"MB" );
            }else if (pack instanceof SuperPackage) {
                SuperPackage sp = (SuperPackage) pack;
                System.out.println("剩余上网流量:" +sp.getFlow()+"MB");
                System.out.println("剩余通话时长:"+sp.getTalkTime()+"分钟");
                System.out.println("剩余短信条数:"+sp.getSmsCount()+"条");
            }
        } else {
            System.out.println("卡号不存在！");
        }
    }
    // 显示消费金额详情
    public void showAmountDetail(String number) {
        MobileCard card = cards.get(number);
        if (card != null) {
            DecimalFormat df = new DecimalFormat("#.0");
            System.out.println("卡号:" + card.getCardNumber());
            System.out.println("用户名:" + card.getUserName());
            double price=card.getSerPackage().getPrice();//月租
            double extra=card.getConsumAmount();//额外
            double total=price+extra;
            System.out.println("套餐月资费:"+price+"元");
            System.out.println("额外费用:"+extra+"元");
            System.out.println("合计消费:"+df.format(total)+"元");
            System.out.println("余额:"+card.getMoney());
        } else {
            System.out.println("卡号不存在！");
        }
    }
    // 添加消费记录
    public void addConsumInfo(String number, ConsumInfo info) {
        // 获取或创建消费记录列表
        List<ConsumInfo> infos = consumInfos.get(number);
        if (infos==null) {
            infos=new ArrayList<>();
            consumInfos.put(number, infos);
        }
        infos.add(info);
    }
    // 使用搜一搜功能
    public void useSoso(String number) {
        MobileCard card=cards.get(number);
        if (card != null) {
            // 定义6个消费场景
            String[] scenes = {
                    "问候客户，谁知其如此难缠",
                    "通知朋友手机换号",
                    "参与环境保护实施方案问卷调查",
                    "观看在线视频",
                    "下载大型文件",
                    "视频会议"
            };
            // 随机选择一个场景
            System.out.println("\n=== 消费场景 ===");
            while (true){
                int sceneIndex = random.nextInt(scenes.length);
                System.out.println(scenes[sceneIndex]);
                switch (sceneIndex) {
                case 0: // 通话90分钟
                    if (card.getSerPackage() instanceof CallService) {
                        CallService ss = (CallService)card.getSerPackage();
                        int extra = ss.call(90, card);
                        if (extra > 0) {
                            System.out.println("通话90分钟,超出套餐" + extra + "分钟");
                            double cost = extra * 0.2;
                            if (card.getMoney() < cost) {
                                System.out.println("余额不足！不能完成本次通话");
                                return;
                            } else {
                                double currentBalance = card.getMoney();
                                card.setMoney(currentBalance - cost);
                                System.out.println("扣除超额通话费用:" + cost + "元，剩余余额：" + card.getMoney());
                            }
                        } else {
                            System.out.println("通话90分钟");
                        }
                        addConsumInfo(number, new ConsumInfo(number, "通话", 90, extra * 0.2));
                    } else {
                        System.out.println("当前套餐不支持通话功能！");
                        continue;
                    }
                    break;
                case 1: // 发送短信50条
                    if (card.getSerPackage() instanceof SendService) {
                        SendService ss = (SendService) card.getSerPackage();
                        int extra = ss.send(50, card);
                        if (extra > 0) {
                            System.out.println("发送短信50条，超出套餐" + extra + "条");
                            double cost = extra * 0.1;
                            if (card.getMoney() < cost) {
                                System.out.println("余额不足！不能完成本次短信发送");
                                return;
                            } else {
                                double currentBalance = card.getMoney();
                                card.setMoney(currentBalance - cost);
                                System.out.println("扣除超额短信费用:" + cost + "元，剩余余额：" + card.getMoney());
                            }
                        } else {
                            System.out.println("发送短信50条");
                        }
                        addConsumInfo(number, new ConsumInfo(number, "短信", 50, extra * 0.1));
                    } else {
                        System.out.println("当前套餐不支持短信功能！");
                        continue;
                    }
                    break;
                case 2: // 发送短信5条
                    if (card.getSerPackage() instanceof SendService) {
                        SendService ss = (SendService) card.getSerPackage();
                        int extra = ss.send(5, card);
                        if (extra > 0) {
                            System.out.println("发送短信5条，超出套餐" + extra + "条");
                            double cost = extra * 0.1;
                            if (card.getMoney() < cost) {
                                System.out.println("余额不足！不能完成本次短信发送");
                                return;
                            } else {
                                double currentBalance = card.getMoney();
                                card.setMoney(currentBalance - cost);
                                System.out.println("扣除超额短信费用：" + cost + "元，剩余余额：" + card.getMoney());
                            }
                        } else {
                            System.out.println("发送短信5条");
                        }
                        addConsumInfo(number, new ConsumInfo(number, "短信", 5, extra * 0.1));
                    } else {
                        System.out.println("当前套餐不支持短信功能！");
                        continue;
                    }
                    break;
                case 3: // 使用流量300MB
                    if (card.getSerPackage() instanceof NetService) {
                        NetService ns = (NetService) card.getSerPackage();
                        int extra = ns.netPlay(300, card);
                        if (extra > 0) {
                            System.out.println("使用流量300MB，超出套餐" + extra + "MB");
                            double cost = extra * 0.1;
                            if (card.getMoney() < cost) {
                                System.out.println("余额不足！无法正常上网");
                                return;
                            } else {
                                double currentBalance = card.getMoney();
                                card.setMoney(currentBalance - cost);
                                System.out.println("扣除超额流量费用：" + cost + "元，剩余余额：" + card.getMoney());
                            }
                        } else {
                            System.out.println("使用流量300MB");
                        }
                        addConsumInfo(number, new ConsumInfo(number, "上网", 300, extra * 0.1));
                    } else {
                        System.out.println("当前套餐不支持上网功能！");
                        continue;
                    }
                    break;
                case 4: // 使用流量800MB
                    if (card.getSerPackage() instanceof NetService) {
                        NetService ns = (NetService) card.getSerPackage();
                        int extra = ns.netPlay(800, card);
                        if (extra > 0) {
                            System.out.println("使用流量800MB，超出套餐" + extra + "MB");
                            double cost = extra * 0.1;
                            if (card.getMoney() < cost) {
                                System.out.println("余额不足！无法正常上网");
                                return;
                            } else {
                                double currentBalance = card.getMoney();
                                card.setMoney(currentBalance - cost);
                                System.out.println("扣除超额流量费用：" + cost + "元，剩余余额：" + card.getMoney());
                            }
                        } else {
                            System.out.println("使用流量800MB");
                        }
                        addConsumInfo(number, new ConsumInfo(number, "上网", 800, extra * 0.1));
                    } else {
                        System.out.println("当前套餐不支持上网功能！");
                        continue;
                    }
                    break;
                case 5: // 使用流量150MB
                    if (card.getSerPackage() instanceof NetService) {
                        NetService ns = (NetService) card.getSerPackage();
                        int extra = ns.netPlay(150, card);
                        if (extra > 0) {
                            System.out.println("使用流量150MB，超出套餐" + extra + "MB");
                            double cost = extra * 0.1;
                            if (card.getMoney() < cost) {
                                System.out.println("余额不足！无法正常上网");
                                return;
                            } else {
                                double currentBalance = card.getMoney();
                                card.setMoney(currentBalance - cost);
                                System.out.println("扣除超额流量费用：" + cost + "元，剩余余额：" + card.getMoney());
                            }
                        } else {
                            System.out.println("使用流量150MB");
                        }
                        addConsumInfo(number, new ConsumInfo(number, "上网", 150, extra * 0.1));
                    } else {
                        System.out.println("当前套餐不支持上网功能！");
                        continue;
                    }
                    break;
            }
            break;}

        }
    }
    // 显示套餐说明
    public void showDescription() {
        System.out.println("===== 套餐说明 =====");
        System.out.println("1. 话痨套餐(58元/月): 通话500分钟/月，短信30条/月");
        System.out.println("2. 网虫套餐(68元/月): 上网流量3GB/月");
        System.out.println("3. 超人套餐(78元/月): 通话200分钟/月，短信50条/月，上网流量1GB/月");
        System.out.println("超出套餐计费:");
        System.out.println("通话:0.2元/分钟");
        System.out.println("短信:0.1元/条");
        System.out.println("上网流量:0.1元/MB");
    }
    //更换套餐
    public void changingPack(String number, String packNum) {
        MobileCard card = cards.get(number);
        if (card==null) {
            System.out.println("卡号不存在！");
            return;
        }
        ServicePackage currentPack=card.getSerPackage();
        ServicePackage newPack = null;
        // 先验证套餐选择是否有效
        while (true){
        switch (packNum) {
            case "1":
                if (currentPack instanceof TalkPackage) {
                    System.out.println("当前已经是话痨套餐，无需变更！");
                    return;
                }
                newPack = new TalkPackage(58);
                break;
            case "2":
                if (currentPack instanceof NetPackage) {
                    System.out.println("当前已经是网虫套餐，无需变更！");
                    return;
                }
                newPack = new NetPackage(68);
                break;
            case "3":
                if (currentPack instanceof SuperPackage) {
                    System.out.println("当前已经是超人套餐，无需变更！");
                    return;
                }
                newPack = new SuperPackage(78);
                break;
            default:
                System.out.println("请输入正确的套餐序号(1-3)");
                packNum=sc.nextLine();
                continue;
        }
        // 检查余额是否足够
        try {
            if (card.getMoney() < newPack.getPrice()) {
                System.out.println("您当前余额不足，需要充值 " +
                        (newPack.getPrice() - card.getMoney()) + " 元才能更换套餐！");
                return;
            }
            // 扣费并更换套餐
            card.setMoney(card.getMoney() - newPack.getPrice());
            card.setSerPackage(newPack);
            // 清零使用量
//            card.setConsumAmount(0);
//            card.setRealTalkTime(0);
//            card.setRealSMSCount(0);
//            card.setRealFlow(0);
            System.out.println("套餐变更成功！");
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }return;
    }}
    public void printConsumInfo1(String number){

    }
    public void printConsumInfo(String number){
        File f=new File("d:\\io\\comsumInfo"+number+".txt");
        if(!consumInfos.containsKey(number)){
            System.out.println("该手机号暂未消费");
            return;
        }
        List<ConsumInfo> list=new ArrayList<>();
        list=consumInfos.get(number);
        StringBuilder sb=new StringBuilder();
        sb.append("*****").append(number).append("消费记录*****\n");
        sb.append("序号\t类型\t数据(通话(条)/上网(MB)/短信(条))\n");
        int i=1;
        for(ConsumInfo c:list){
            String type="";
            if(c.type.equals("通话"))type="分钟";
            else if(c.type.equals("上网"))type="MB";
            else if(c.type.equals("短信"))type="条";
            sb.append(i+".\t"+c.type+"\t"+c.consumData+type+"\n");
            i++;
        }
        try {
            BufferedWriter bw=new BufferedWriter(new FileWriter(f));
            bw.write(sb.toString());
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sb);
    }
    //反序列化
    public void input(){
        File file = new File("d:\\ioii\\consume.txt");
        if (!file.exists()) {
            consumInfos = new HashMap<>(); // 初始化空的 consumInfos
            return;
        }
        try (FileInputStream fis=new FileInputStream("d:\\ioii\\consume.txt");
        ObjectInputStream ois=new ObjectInputStream(fis)){
        consumInfos=(Map<String, List<ConsumInfo>>) ois.readObject();
        cards=(Map<String, MobileCard>) ois.readObject();
        }catch (EOFException e) {
            consumInfos = new HashMap<>();
        }catch (Exception e) {
            e.printStackTrace();
            consumInfos = new HashMap<>(); // 其他异常时初始化
        }
    }
    //序列化
    public void output(){
        File f=new File("d:\\ioii\\consume.txt");
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
        }
        try(FileOutputStream fos=new FileOutputStream(f)) {
            ObjectOutputStream obs=new ObjectOutputStream(fos);
            obs.writeObject(consumInfos);
            obs.writeObject(cards);
            System.out.println("客户信息保存成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    // 充值
    public void chargeMoney(String number, double money) {
        MobileCard card = cards.get(number);
        if (card!=null) {
            if (money<50) {
                System.out.println("充值金额至少50元！");
                return;
            }
            card.setMoney(card.getMoney()+money);
            addConsumInfo(number, new ConsumInfo(number, "充值", 0, money));
            System.out.println("充值成功！当前余额:"+card.getMoney()+"元");
        } else {
            System.out.println("卡号不存在！");
        }
    }
    // 从文件读取资费说明
    public void showDescriptionFromFile() {
        try (BufferedReader br=new BufferedReader(new FileReader("d:\\io\\money.txt"))) {
            String line;
            System.out.println("\n===== 消费说明 =====");
            while ((line=br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("资费说明文件不存在，将显示默认说明");
            showDescription();
        } catch (IOException e) {
            System.out.println("读取资费说明失败，将显示默认说明");
            showDescription();
        }
    }
}
